<?php

/* * *
 * Processed form data into a proper post array, uses wp_insert_post() to add post. 
 * 
 * @param array $pfs_data POSTed array of data from the form
 */
require('../../../wp-load.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

/**
 * Create post from form data, including uploading images
 * @param array $post
 * @param array $files
 * @return string success or error message.
 */
function pfs_submit($post, $files) {

    $pfs_options_arr = get_option('pfs_options');
    $pfs_options = $pfs_options_arr[0];
    $pfs_data = $post;
    $pfs_files = $files;
    //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($pfs_data, true)."</pre>\n";
    //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($pfs_files, true)."</pre>\n";

    $title = $pfs_data['title'];
    $post_type = $pfs_data['post_type'];
    $postcontent = $pfs_data['postcontent'];

    $name = (array_key_exists('name', $pfs_data)) ? esc_html($pfs_data['name'], array()) : '';
    $email = (array_key_exists('email', $pfs_data)) ? sanitize_email($pfs_data['email']) : '';

    $taxonomies = array();

    $imgAllowed = 0;
    $result = Array(
        'image' => "",
        'error' => "",
        'success' => "",
        'post' => ""
    );
    $success = False;
    $upload = False;

    if (!current_user_can('publish_posts') && $pfs_options['allow_anon'] && $pfs_options['enable_captcha']) {
        require_once('recaptchalib.php');
        $privatekey = $pfs_options_arr['recaptcha_private_key'];
        $resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
    }
    if (!current_user_can('publish_posts') && $pfs_options['allow_anon'] && $pfs_options['enable_captcha'] && !$resp->is_valid) {
        // What happens when the CAPTCHA was entered incorrectly
        $result['error'] = printf(__("Incorrect reCAPTCHA: %s", 'pfs_domain'), $resp->error);
    } else {
        //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($pfs_files['image']['name'], true)."</pre>\n";
        if (array_key_exists('image', $pfs_files)) {
            /* play with the image */
            switch (True) {
                case (1 < count($pfs_files['image']['name'])):
                    // multiple file upload
                    $result['image'] = "multiple";
                    $file = $pfs_files['image'];
                    for ($i = 0; $i < count($file['tmp_name']); $i++) {
                        if ('' != $file['tmp_name'][$i]) {
                            $imgAllowed = (getimagesize($file['tmp_name'][$i])) ? True : ('' == $file['name'][$i]);
                            if ($imgAllowed) {
                                $upload[$i + 1] = upload_image(array('name' => $pfs_files["image"]["name"][$i], 'tmp_name' => $pfs_files["image"]["tmp_name"][$i]));
                                if (False === $upload[$i + 1]) {
                                    $result['error'] = __("There was an error uploading the image.", 'pfs_domain');
                                } else {
                                    $success[$i + 1] = True;
                                }
                            } else {
                                $result['error'] = __("Incorrect filetype. Only images (.gif, .png, .jpg, .jpeg) are allowed.", 'pfs_domain');
                            }
                        }
                    }
                    break;
                case ((1 == count($pfs_files['image']['name'])) && ('' != $pfs_files['image']['name'][0]) ):
                    // single file upload
                    $file = $pfs_files['image'];
                    $result['image'] = 'single';
                    $imgAllowed = (getimagesize($file['tmp_name'][0])) ? True : ('' == $file['name'][0]);
                    if ($imgAllowed) {
                        $upload[1] = upload_image(array('name' => $file["name"][0], 'tmp_name' => $file["tmp_name"][0]));
                        //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($upload, true)."</pre>\n";
                        if (False === $upload[1]) {
                            $result['error'] = __("There was an error uploading the image.", 'pfs_domain');
                        } else {
                            $success[1] = True;
                        }
                    } else {
                        $result['error'] = __("Incorrect filetype. Only images (.gif, .png, .jpg, .jpeg) are allowed.", 'pfs_domain');
                    }
                    break;
                default:
                    $result['image'] = 'none';
            }
        }
        if ('' != $result['error'])
            return $result; // fail if the image upload failed.






            
//echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($upload, true)."</pre>\n";
        //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($success, true)."</pre>\n";

        /* manipulate $pfs_data into proper post array */
        $has_content_things = ($title != '') && ($postcontent != '');
        if (!current_user_can('publish_posts') && $pfs_options['allow_anon'])
            $has_content_things = $has_content_things && ($name != '') && is_email($email);
        if ($has_content_things) {
            $content = $postcontent;
            if (!current_user_can('publish_posts') && $pfs_options['allow_anon'])
                $content .= apply_filters('pfs_submittedby_text', "<p>Submitted by <a href='mailto:$email'>$name</a></p>");
            if (is_user_logged_in()) {
                global $user_ID;
                get_currentuserinfo();
            }
//            if (is_array($success)){
//                foreach(array_keys($success) as $i){
//                    $imgtag = "[!--image$i--]";
//                    if (False === strpos($content,$imgtag)) $content .= "\n\n$imgtag";
//                    $content = str_replace($imgtag, wp_get_attachment_link( $upload[$i], $pfs_options['wp_image_size']), $content);
//                }
//            }
//            //if any [!--image#--] tags remain, they are invalid and should just be deleted.
//            $content = preg_replace('/\[\!--image\d*--\]/','',$content);
            // $terms[{tax name}] = array(term1, term2, etc)
            if (array_key_exists('terms', $pfs_data)) {
                foreach ($pfs_data['terms'] as $taxon => $terms) {
                    if (!is_taxonomy_hierarchical($taxon)) {
                        $pfs_data['terms'][$taxon] = implode(',', $terms);
                    }
                }
            }
            $current_user = wp_get_current_user();

            $postarr = array();
//            $postarr = array(
//			'post_author' => 1,
//			'post_content' => 'This is event content!',
//			'EventAllDay' => false,
//			'EventHideFromUpcoming' => true,
//			'EventOrganizerID' => 279,
//			'EventVenueID' => 280,
//			'EventShowMapLink' => true,
//			'EventShowMap' => true,
//			'EventStartDate' => '2015-01-01',
//			'EventEndDate' => '2015-01-03',
//			'EventStartHour' => '01',
//			'EventStartMinute' => '15',
//			'EventStartMeridian' => 'am',
//			'EventEndHour' => '03',
//			'EventEndMinute' => '25',
//			'EventEndMeridian' => 'pm'
//		);
            
            $postarr['post_title'] = $title;
            $postarr['post_content'] = apply_filters('comment_text', $content);
            $postarr['comment_status'] = $pfs_options['comment_status'];
            $postarr['post_status'] = ($current_user->data->ID == 1) ? 'publish' : $pfs_options['post_status']; // add by suraj : check admin for directly post
            $postarr['post_author'] = ( is_user_logged_in() ) ? $user_ID : $pfs_options['default_author'];
            $postarr['tax_input'] = (array_key_exists('terms', $pfs_data)) ? $pfs_data['terms'] : array();
            $postarr['post_type'] = ($post_type) ? $post_type : $pfs_options['post_type'];
            //

            if ($post_type == 'event') {
                
                
                //1. create event
                //2. create organizer (if new organizer is selected)
                //3. create venue (if new venue is selected)
                //4. update EventOrganizerID,  EventVenueID
                $start_date = @$pfs_data['start_date'];
                $start_hour = @$pfs_data['start_hour'];
                $start_minute = @$pfs_data['start_minute'];
                $start_meridian = @$pfs_data['start_meridian'];
                
                $end_date = @$pfs_data['end_date'];
                $end_hour = @$pfs_data['end_hour'];
                $end_minute = @$pfs_data['end_minute'];
                $end_meridian = @$pfs_data['end_meridian'];
                
                
                
                
                $event_cost = @$pfs_data['cost'];
                $event_url = @$pfs_data['website'];

                $organizer_id = @$pfs_data['organizer_id'];
                $organizer_name = @$pfs_data['organizer_name'];
                $organizer_phone = @$pfs_data['organizer_phone'];
                $organizer_website = @$pfs_data['organizer_website'];
                $organizer_email = @$pfs_data['organizer_email'];

                $venue_id = @$pfs_data['venue_id'];
                $venue_name = @$pfs_data['venue_name'];
                $venue_address = @$pfs_data['venue_address'];
                $venue_city = @$pfs_data['venue_city'];
                $venue_phone = @$pfs_data['venue_phone'];
                $venue_url = @$pfs_data['venue_website'];
                
                $organizer_id = (is_numeric($organizer_id) && $organizer_id>0)?$organizer_id:0;
                $venue_id = (is_numeric($venue_id) && $venue_id>0)?$venue_id:0;
                //validation
                if($start_date=="" || $end_date=="" || $title=="" || $content=="" || $organizer_id<0 || $venue_id<0 || $event_cost==""){
                    $result['error'] = __("You've left a some field empty. Please check and try again.", 'pfs_domain');
                    return $result;
                }else if($organizer_id==0 && $organizer_name=="" ){
                    $result['error'] = __("You've left organizer field empty, Create new organizer or choose any from list.", 'pfs_domain');
                    return $result;
                }else if($venue_id==0 && $venue_name=="" ){
                    $result['error'] = __("You've left venue field empty, Create new venue or choose any one from list.", 'pfs_domain');
                    return $result;
                }
                

                $postarr['EventStartDate'] = $start_date;
                $postarr['EventEndDate'] = $end_date;
                $postarr['EventOrganizerID'] = $organizer_id;
                $postarr['EventVenueID'] = $venue_id;
                $postarr['EventCost'] = $event_cost;
                $postarr['EventURL'] = $event_url;
                $postarr['EventCurrencySymbol'] = '';
                $postarr['EventShowMapLink'] = false;
                $postarr['EventShowMap'] = false;
                $postarr['EventAllDay'] = false;
                $postarr['EventHideFromUpcoming'] = true;
                $postarr['EventStartHour'] = $start_hour;
                $postarr['EventStartMinute'] = $start_minute;
                $postarr['EventStartMeridian'] = $start_meridian;
                $postarr['EventEndHour'] = $end_hour;
                $postarr['EventEndMinute'] = $end_minute;
                $postarr['EventEndMeridian'] = $end_meridian;
                $ret_event_id = TribeEventsAPI::createEvent($postarr);
                if ($ret_event_id > 0) {
                    if ($organizer_id < 1 || !is_numeric($organizer_id)) {
                        $argsOrg = array(
                            'Organizer' => $organizer_name,
                            'Phone' => $organizer_phone,
                            'Website' => $organizer_website,
                            'Email' => $organizer_email,
                        );
                        $ret_organizer_id = TribeEventsAPI::createOrganizer($argsOrg);
                        //then update post meta value for EventOrganizerID
                        update_post_meta($ret_event_id, '_EventOrganizerID', $ret_organizer_id);
                    }
                    if ($venue_id < 1 || !is_numeric($venue_id)) {
                        $argsVenue = array(
                            'Venue' => $venue_name,
                            'Address' => $venue_address,
                            'City' => $venue_city,
                            'Phone' => $venue_phone,
                            'URL' => $venue_url,
                        );
                        $ret_venue_id = TribeEventsAPI::createVenue($argsVenue);
                        //then update post meta value for EventVenueID
                        update_post_meta($ret_event_id, '_EventVenueID', $ret_venue_id);
                    }
                    //set to featured image
                    if (is_array($success)) {
                        foreach (array_keys($success) as $i) {
                            if (set_post_thumbnail($ret_event_id, $upload[$i])) {
                                break;
                            }
                        }
                    }
                    //end featured image

                    $msg = __("Event added, please wait to return to the previous page.", 'pfs_domain');
                    $result['success'] = $msg;
                    $result['post'] = $ret_event_id;
                } else {
                    $msg = __("Unable to insert event- unknown error.", 'pfs_domain');
                    $result['error'] = $msg;
                }
            } else { //for other like information, post, pages etc
                $post_id = wp_insert_post($postarr);
                if (0 == $post_id) {
                    $msg = __("Unable to insert post- unknown error.", 'pfs_domain');
                    $result['error'] = $msg;
                } else {
                    //set to featured image
                    if (is_array($success)) {
                        foreach (array_keys($success) as $i) {
                            if (set_post_thumbnail($post_id, $upload[$i])) {
                                break;
                            }
                        }
                    }
                    //end featured image

                    $msg = __("Post added, please wait to return to the previous page.", 'pfs_domain');
                    $result['success'] = $msg;
                    $result['post'] = $post_id;
                }
            }
            //  echo "<script>alert('".$msg."')</script>";
        } else {
            $result['error'] = __("You've left a some field empty. Please check and try again.", 'pfs_domain');
        }
    }
    return $result;
}

/**
 * Upload images
 */
function upload_image($image) {
    $file = wp_upload_bits($image["name"], null, file_get_contents($image["tmp_name"]));
    //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">";
    //var_dump($file);
    //echo "</pre>\n";
    if (false === $file['error']) {
        $wp_filetype = wp_check_filetype(basename($file['file']), null);
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => preg_replace('/\.[^.]+$/', '', basename($file['file'])),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        $attach_id = wp_insert_attachment($attachment, $file['file']);
        // you must first include the image.php file
        // for the function wp_generate_attachment_metadata() to work
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attach_id, $file['file']);
        wp_update_attachment_metadata($attach_id, $attach_data);
        return $attach_id;
    } else {
        //TODO: er, error handling?
        return false;
    }
}

if (!empty($_POST)) {
    $pfs = pfs_submit($_POST, $_FILES);
    echo json_encode($pfs);
    //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($pfs, true)."</pre>\n";
} else {
    /* TODO: translate following */
    _e('You should not be seeing this page, something went wrong.', 'pfs_domain');
    echo "<a href='" . get_bloginfo('url') . "'>" . __('Go home?', 'pfs_domain') . "</a>";
}

//get_footer();
?>
